﻿@using Volo.Abp.Localization
@using System.Globalization
@using System.Collections.Immutable
@using Microsoft.AspNetCore.RequestLocalization
@inject ILanguageProvider LanguageProvider
@inject NavigationManager NavigationManager
@inject IAbpRequestLocalizationOptionsProvider RequestLocalizationOptionsProvider
@if (_otherLanguages != null && _otherLanguages.Any())
{
    <div>
        <label>@_currentLanguage.DisplayName</label>
        <Select Value="@_currentLanguage" OnSelectedItemChanged="@SetCulture">
            <Options>
                @foreach (var language in _otherLanguages)
            {
                <SelectOption Text="@language.DisplayName" Value="@language.UiCultureName" />
            }
        </Options>
    </Select>
</div>
}
@code {
    private IReadOnlyList<LanguageInfo> _otherLanguages;
    private LanguageInfo _currentLanguage;

    protected override async Task OnInitializedAsync()
    {
        var languages = await LanguageProvider.GetLanguagesAsync();
        var currentLanguage = languages.FindByCulture(
            CultureInfo.CurrentCulture.Name,
            CultureInfo.CurrentUICulture.Name
            );

        if (currentLanguage == null)
        {
            var localizationOptions = await RequestLocalizationOptionsProvider.GetLocalizationOptionsAsync();
            if (localizationOptions.DefaultRequestCulture != null)
            {
                currentLanguage = new LanguageInfo(
                    localizationOptions.DefaultRequestCulture.Culture.Name,
                    localizationOptions.DefaultRequestCulture.UICulture.Name,
                    localizationOptions.DefaultRequestCulture.UICulture.DisplayName);
            }
            else
            {
                currentLanguage = new LanguageInfo(
                    CultureInfo.CurrentCulture.Name,
                    CultureInfo.CurrentUICulture.Name,
                    CultureInfo.CurrentUICulture.DisplayName);
            }
        }
        _currentLanguage = currentLanguage;
        _otherLanguages = languages.Where(l => l != _currentLanguage).ToImmutableList();
    }
    private Task SetCulture(SelectedItem item)
    {
        var languate = this._otherLanguages.Where(x => x.DisplayName == item.Text).First();
        this.ChangeLanguage(languate);
        return Task.CompletedTask;
    }
    private void ChangeLanguage(LanguageInfo language)
    {
        var relativeUrl = NavigationManager.Uri.RemovePreFix(NavigationManager.BaseUri).EnsureStartsWith('/');
        NavigationManager.NavigateTo(
            $"/Abp/Languages/Switch?culture={language.CultureName}&uiCulture={language.UiCultureName}&returnUrl={relativeUrl}",
            forceLoad: true
        );
    }
}
